import { sys } from "cc";
import { HTML5 } from "cc/env";
import EventEmitter from 'eventemitter3'
type Platform = "android" | "ios" | "web";

export abstract class BaseJSBridge<T extends EventEmitter.ValidEventTypes> extends EventEmitter<T> {
    protected readonly platform: Platform;

    constructor(platform?: Platform) {
        super()
        this.platform = platform ?? this.detectPlatform();
    }


    /** 
     * Cocos 里：
     * - HTML5 环境：通过 URL 参数读取 platform（默认 web）  
     * - 原生环境：通过 cc.sys.platform 判断 android/ios  
     */
    private detectPlatform(): Platform {
        if (HTML5) {
            const params = new URLSearchParams(window.location.search);
            return (params.get("platform") as Platform) ?? "web";
        } else {
            // 原生平台
            switch (sys.platform) {
                case sys.Platform.ANDROID:
                    return "android";
                case sys.Platform.IOS:
                    return "ios";
                default:
                    return "web";
            }
        }
    }

    /** 简化判断，方便子类调用 */
    protected get isAndroid(): boolean {
        return this.platform === "android";
    }
    protected get isIOS(): boolean {
        return this.platform === "ios";
    }
    protected get isWeb(): boolean {
        return this.platform === "web";
    }
}